package com.archgeek.java.udp.v3zk;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.util.Random;

/**
 * @author pizhihui
 * @date 2023-03-08 15:59
 */
public class LookForLeader {

    public static void main(String[] args) {

        DatagramSocket socket;
        try {
            socket = new DatagramSocket();
            socket.setSoTimeout(200);
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }

        byte[] reqBytes = new byte[4];
        ByteBuffer reqBuffer = ByteBuffer.wrap(reqBytes);


        int xid = new Random().nextInt();
        System.out.println("xid=" + xid);

        DatagramPacket reqPacket = new DatagramPacket(reqBytes, reqBytes.length);

        // 3*8+4=28
        byte[] respBytes = new byte[28];
        DatagramPacket respPacket = new DatagramPacket(respBytes, respBytes.length);
        ByteBuffer respBuffer = ByteBuffer.wrap(respBytes);

        reqBuffer.clear();
        reqBuffer.putInt(xid);
        reqPacket.setLength(4);

        // 这里可以发送到多台机器
        reqPacket.setSocketAddress(new InetSocketAddress("127.0.0.1", 2889));
        try {
            socket.send(reqPacket);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            socket.receive(respPacket);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("收到数据.....length=" + respPacket.getLength());
        respBuffer.clear();

        System.out.println("-----------");
        int receiveId = respBuffer.getInt();
        long peerId = respBuffer.getLong();
        long myid = respBuffer.getLong();
        long zxid = respBuffer.getLong();
        System.out.println("receiveId=" + receiveId +
                ",peerId=" + peerId + ",myid=" + myid + ",zxid=" + zxid);


    }

}
